<template>
  <CommonPage title="积分规则定义" content-row>
    <div class="w-72 pr-4 flex flex-col">
      <div class="mb-4">
        <span class="text-lg font-semibold text-color-header">商品类别</span>
      </div>
      <div class="flex-1 overflow-auto">
        <a-skeleton v-if="dictLoading" active loading :avatar="false"></a-skeleton>
        <a-tree
          v-else-if="dictData.length > 0"
          v-model:selectedKeys="selectedKeys"
          :tree-data="dictData"
          :field-names="{ title: 'label', key: 'value' }"
          block-node
          show-line
          show-icon
          default-expand-all
        >
        </a-tree>
        <SlEmpty v-else />
      </div>
    </div>
    <div class="flex-1 flex flex-col overflow-hidden">
      <div class="flex flex-row items-center mb-3">
        <div class="flex-1">
          <span class="text-lg font-semibold text-color-header">商品列表</span>
        </div>
        <div>
          <a-button type="primary" @click="batchRatio">批量设置积分</a-button>
        </div>
      </div>
      <div class="flex-1 overflow-hidden">
        <SlTable
          class="table-pg-px0"
          :columns="columns"
          row-key="id"
          :data-source="tableData"
          :pagination="pagination"
          :loading="tableLoading"
        >
          <template #bodyCell="{ column, record }">
            <div v-if="column.key === 'oper'">
              <a @click="updateRatio(record)">修改积分</a>
            </div>
            <!-- <div v-else-if="column.dataIndex === 'pointRedemptionRatio'" style="width: 50px">
              {{ record.pointRedemptionRatio }}
            </div> -->
            <WidthFitCell
              v-else
              :title="column.title"
              :value="record[column.dataIndex as string]"
              :record="record"
              :custom-render="column.customRender"
            />
          </template>
        </SlTable>
      </div>
    </div>
    <a-modal
      v-model:visible="ratioModalVisible"
      :title="ratioModalTitle"
      :ok-button-props="{ loading: okLoading }"
      @ok="handleOk"
    >
      <a-input-number v-model:value="curRatio" placeholder="请输入积分" :min="0" :max="9999" style="width: 100%" />
    </a-modal>
  </CommonPage>
</template>
<script setup lang="ts">
import { onMounted, ref, watch } from "vue";
import { useCURD } from "/@/hooks/useCURD";
import { TableProps, message } from "ant-design-vue";
import { getDictOptions } from "/@/api/main/system";
import { DictTypeCode } from "/@/api/main/system/models";
import {
  CURDAction,
  FormItemComponentType,
  FormItemData,
  ShowCURDModalOptions,
  CURDDialogExpose,
  CURDModalEvent,
} from "/@/components/CURDDialog/models";
import { ProductFileItem, CompanyType, SupplierItem } from "/@/api/main/pis/models";
import { Api, updateIntroduction, updateProductRatio } from "/@/api/main/pis";
import { SelectOptionItem } from "/@/types/antd";
import { enumToOptions, getLabelByValueFromEnum, priceRender } from "/@/utils/common";
import { findItemByKey } from "/@/utils/treeData";
import { updateBatchRatio } from "/@/api/main/member";
/**
 * 商品类别
 */
const dictData = ref<SelectOptionItem[]>([]);
const selectedKeys = ref<number[]>([]);
const dictLoading = ref(true);
onMounted(async () => {
  const data = await getDictOptions({ typeCode: DictTypeCode.productCategory });
  dictLoading.value = false;
  if (data) {
    dictData.value = data;
    if (data.length > 0) {
      selectedKeys.value = [data[0].value as number];
    }
  }
});
watch(selectedKeys, (keys) => {
  reloadTable({ model: { productTypeId: keys.length > 0 ? keys[0] : "" } });
});
/**
 * 商品表格
 */
const columns = ref<TableProps<ProductFileItem>["columns"]>([
  {
    title: "编码",
    dataIndex: "productCode",
  },
  {
    title: "条码",
    dataIndex: "barCode",
  },
  {
    title: "品名",
    dataIndex: "name",
  },
  {
    title: "积分比率",
    dataIndex: "pointRedemptionRatio",
  },
  {
    title: "供应商",
    dataIndex: "supplierName",
  },
  {
    title: "商品类别",
    dataIndex: "productType",
  },
  {
    title: "商城分类",
    dataIndex: "mallClass",
  },
  {
    title: "产地",
    dataIndex: "productArea",
  },
  {
    title: "规格",
    dataIndex: "specifications",
  },
  {
    title: "计量单位",
    dataIndex: "measurementUnit",
  },
  {
    title: "克重",
    dataIndex: "weight",
  },
  {
    title: "有效期标准",
    dataIndex: "validityCriteria",
  },
  {
    title: "进货价",
    dataIndex: "purchasePrice",
    customRender: priceRender,
  },
  {
    title: "售价",
    dataIndex: "price",
    customRender: priceRender,
  },
  {
    title: "批发价",
    dataIndex: "wholesalePrice",
    customRender: priceRender,
  },
  {
    title: "税率",
    dataIndex: "taxRate",
  },
  {
    title: "保存方式",
    dataIndex: "saveAs",
  },
  {
    title: "状态",
    dataIndex: "status",
  },
  {
    title: "操作",
    key: "oper",
    width: 100,
    fixed: "right",
  },
]);

const { pagination, tableData, tableLoading, curd, reloadTable } = useCURD<ProductFileItem>({
  getPageUrl: Api.productFilePage,
  cudUrl: Api.productFiles,
  loadOnMounted: false,
});
/**
 * ratio
 */
const ratioModalVisible = ref(false);
const ratioModalTitle = ref("");
const curRatio = ref<number>();
let curInfoToUpdateRatio: { productTypeId?: number; productId?: number } = {};
const okLoading = ref(false);
function batchRatio() {
  const re = findItemByKey(dictData.value, selectedKeys.value[0], { keyName: "value" });
  if (re) {
    curRatio.value = void 0;
    const targetDict = re.item;
    curInfoToUpdateRatio = { productTypeId: targetDict.value as number };
    ratioModalTitle.value = `${targetDict.label}-设置积分`;
    ratioModalVisible.value = true;
  }
}
function updateRatio(record: ProductFileItem) {
  curInfoToUpdateRatio = { productId: record.id };
  curRatio.value = void 0;
  ratioModalTitle.value = `${record.name}-设置积分`;
  ratioModalVisible.value = true;
}
async function handleOk() {
  if (!curRatio.value) {
    return message.info("请输入积分");
  }
  if (curInfoToUpdateRatio.productTypeId) {
    okLoading.value = true;
    const re = await updateBatchRatio(curInfoToUpdateRatio.productTypeId, curRatio.value);
    okLoading.value = false;
    ratioModalVisible.value = false;
    if (re === undefined) {
      message.success("设置成功");
      reloadTable();
    }
  } else if (curInfoToUpdateRatio.productId) {
    okLoading.value = true;
    const re = await updateProductRatio(curInfoToUpdateRatio.productId, curRatio.value);
    okLoading.value = false;
    ratioModalVisible.value = false;
    if (re === undefined) {
      message.success("设置成功");
      reloadTable();
    }
  }
}
</script>
<style lang="less">
.mp-modal {
  .ant-modal {
    top: 0;
  }
}
</style>
